//
// Created by Felix on 24-4-27.
//

#include "common.hpp"

std::string uuidString() {
    std::random_device rd;
    auto seed_data = std::array<int, std::mt19937::state_size>{};
    std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
    std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
    std::mt19937 generator(seq);

    std::string id = uuids::to_string(uuids::uuid_random_generator{generator}());
    return id;
}

oatpp::String &trim(
        oatpp::String &string, const oatpp::String &characters
) {
    auto str = std::string(*string);
    trim(str, std::string(*characters));
    string = str;
    return string;
}

std::string &trim(
        std::string &str, const std::string &characters
) {
    str.erase(0, str.find_first_not_of(characters));
    str.erase(str.find_last_not_of(characters) + 1);
    return str;
}

std::vector<std::string> splitAndRemoveEmpty(const std::string &str) {
    std::istringstream iss(str);
    std::vector<std::string> tokens;

    std::string token;
    while (iss >> token) { // >> 操作符会自动忽略空白字符
        tokens.push_back(token);
    }

    return tokens; // 返回不含空字符串的vector
}

// 使用空格连接字符串
std::string joinWithSpaces(const std::vector<std::string> &lines) {
    return std::accumulate(
            lines.begin(), lines.end(), std::string{},
            [](const std::string &a, const std::string &b) { return a + " " + b; }
    );
}

// 使用SHA-256哈希字符串
std::string sha256(std::string data) {
    CryptoPP::byte const *pbData = (CryptoPP::byte *) data.data();
    unsigned int nDataLen = data.length();
    CryptoPP::byte abDigest[CryptoPP::SHA256::DIGESTSIZE];

    CryptoPP::SHA256().CalculateDigest(abDigest, pbData, nDataLen);

    std::stringstream ss;
    for (unsigned char i: abDigest) {
        ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(i);
    }
    return ss.str();
}

/**
 * 获取当前时间戳
 * @return int64_t
 */
int64_t getCurrentTime() {
    std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
    return std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
}
